import 'dart:convert';

import 'package:baselib/utils/load_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:baselib/utils/navigator_util.dart';
import 'package:baselib/utils/toast_util.dart';
import 'package:baselib/widgets/comm_message_gradient_dialog.dart';
import 'package:baselib/widgets/comm_select_gradient_dialog.dart';
import 'package:baselib/widgets/dialog_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:framelib/base/base_view_model.dart';
import 'package:framelib/config/api_config.dart';
import 'package:framelib/config/route_config.dart';
import 'package:framelib/net/baseentity.dart';
import 'package:framelib/utils/nim_sdk_util.dart';
import 'package:framelib/utils/string_util.dart';
import 'package:framelib/widgets/invite_onmic_gradient_dialog.dart';
import 'package:framelib/widgets/room_other_info_gradient_dialog.dart';
import 'package:framelib/widgets/room_self_info_gradient_dialog.dart';
import 'package:framelib/widgets/room_top_widget.dart';
import 'package:framelib/widgets/send_comment_widget.dart';
import 'package:module_business/module_chat/model/gift_entity.dart';
import 'package:module_business/module_comm/model/user_entity.dart';
import 'package:module_business/module_comm/model/user_params_model.dart';
import 'package:module_business/module_index/model/index_room_item_entity.dart';
import 'package:module_business/module_index/model/member_status_entity.dart';
import 'package:module_business/module_index/model/voice_person_entity.dart';
import 'package:module_business/module_index/service/module_index_service.dart';
import 'package:get/get.dart';
import 'package:module_business/module_index/view/room_gifts_bottom_sheet_widget.dart';
import 'package:module_business/module_my/service/module_my_service.dart';
import 'package:nim_core/nim_core.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:agora_rtc_engine/agora_rtc_engine.dart';

class MyRoomViewModel extends BaseViewModel<ModuleIndexService> with GetTickerProviderStateMixin{
  ModuleIndexService moduleIndexService;
  ModuleMyService moduleMyService;
  IndexRoomItemEntity roomInfo;
  // RxBool isCommentOpen = false.obs;

  //云信房间信息
  Rx<NIMChatroomInfo> roomYxInfo = NIMChatroomInfo().obs;
  //当用户被踢出聊天室或者聊天室关闭时，会触发被踢回调。
  // blacklisted	被拉黑了
  // dismissed	聊天室已经被关闭
  // byConflictLogin	被其他端踢出
  // byManager	被管理员踢出
  // unknown	未知（出错情况）
  Rx<NIMChatroomKickOutEvent> nimChatroomKickOutEvent = null.obs;
  //聊天室聊天信息
  Rx<List<NIMChatroomMessage>> chatRoomMsgs = Rx<List<NIMChatroomMessage>>([]);
  //聊天室成员id集合信息
  // List<String> chatRoomMemberIds = [];
  //聊天室成员信息
  // List<NIMChatroomMember> chatRoomMembers= [];
  //聊天室服务端成员信息
  List<UserEntity> chatRoomServiceMembers= [];
  //聊天室服务端成员云信id信息
  List<String> chatRoomServiceMembersAccIds= [];
  //说话的成员
  Rx<List<AudioVolumeInfo>> speakers = Rx<List<AudioVolumeInfo>>([]);
  //欢迎数据  MemberStatusEntity
  Rx<List<MemberStatusEntity>> attachmentMemberMessages = Rx<List<MemberStatusEntity>>([]);


  //对于声网Agora
  // String appId = 'db7b5539615a47ee82e25dd86e10edf1';
  // String channelId = 'tp';
  // String token = '007eJxTYBDYu2pXoFfTRbsJ0jz7X8upWuxeUvnpSgVPv846XqOD5TUKDClJ5kmmpsaWZoamiSbmqakWRqlGpikpFmaphgapKWmGLl+UUxoCGRm6d91gZGSAQBCfiaGkgIEBANR5Hlw=';

  RtcEngine _engine;

  ///初始化状态
  Future<bool> initStatus;

  ///当前 controller
  // VideoViewController currentController;

  ///是否加入聊天
  bool isJoined = false;

  /// 记录加入的用户id
  // Map<int, VideoViewController> remoteControllers = {};
  //查询当前用户与房间的关系
  VoicePersonEntity currVoicePersonEntity = VoicePersonEntity();

  //默认麦位集合
  List<VoicePersonEntity> defaultPersons = [];
  List<String> roomTotalAccounts = [];
  //是否是被迫离开
  bool isForceLeave = false;
  //我关注的人的id集合
  List<int> myFollowIds = [];
  //是否收藏
  RxBool isCollect = false.obs;
  //听是否打开
  RxBool voiceListenOpen = false.obs;
  //说是否打开
  RxBool speakRecordOpen = true.obs;
  //是否上麦
  bool isOnMic = false;


  @override
  //ModuleMyService
  ModuleIndexService createService(){
    moduleMyService = ModuleMyService();
    return moduleIndexService = ModuleIndexService();
  }

  @override
  void onInit() {
    // myRoom = UserParamsModel.instance.myRoom;
    roomInfo = (Get.arguments??{})['roomItem'];
    defaultPersons = (roomInfo?.voiceMikeDetailVoList??[]).where((element) => (element?.mikeIndex!=(-1))).toList();
    //设置初始化数据
    setInitData();
    super.onInit();
  }
  @override
  void onReady() {
    super.onReady();
  }

  setInitData() async{
    //查询房主
    // await getPersonByUserId(roomInfo?.homeownerId,0);
    //查询是否收藏了此房间
    checkCollect();
    //获取我关注的列表
    getMyFollows();
    //查询此用户和此房间的关系
    await queryUserRoomRelationType();
    //设置进入房间成功
    _setJoinRoomSuccess();
    //获取聊天室信息
    getRommInfo();
    //拉取历史消息
    _fetchMessageHistory();
    //设置消息监听
    _setLinsener();
    LogUtil.d('myRoom--->${roomInfo?.toJson()}');
    enableAgroJoin();
  }
  enableAgroJoin() async{
    try{
      initStatus = _requestPermissionIfNeed().then((value) async {
        await _initEngine();
        ///构建当前用户 currentController
        // currentController = VideoViewController(
        //   rtcEngine: _engine,
        //   // canvas: VideoCanvas(uid: int.parse(UserParamsModel.instance.userId)),
        //   canvas: VideoCanvas(uid: 0),
        // );
        return true;
      }).whenComplete((){
        update();
      });
    }catch(e){
      LogUtil.d("AgoraSDKUtil--->registerEventHandler e = ${e?.toString()}");
    }
  }
  Future<void> _requestPermissionIfNeed() async {
    await [Permission.microphone, Permission.camera].request();
  }

  Future<void> _initEngine() async {
    //创建 RtcEngine
    _engine = createAgoraRtcEngine();
    // 初始化 RtcEngine
    await _engine.initialize(RtcEngineContext(
      appId: ApiConfig.agora_app_id,
      // appId: appId,
    ));

    await _engine.enableAudioVolumeIndication(interval: 800,smooth: 3,reportVad: true);
    _engine.registerEventHandler(RtcEngineEventHandler(
        onClientRoleChanged: (
            RtcConnection connection,
            ClientRoleType oldRole,
            ClientRoleType newRole,
            ClientRoleOptions newRoleOptions){
          LogUtil.d('AgoraSDKUtil---> onClientRoleChanged,'
              ',localUid: ${connection?.localUid},'
              ',oldRole: ${oldRole?.name},'
              ',newRole: ${newRole?.name},'
              ' newRoleOptions: ${newRoleOptions?.toJson()}'
          );
        },

        //说话的成员回调
        onAudioVolumeIndication: (RtcConnection connection,
            List<AudioVolumeInfo> speakersTemp, int speakerNumber, int totalVolume) {
          speakersTemp.forEach((element) {
            var uid = element.uid;
            var volume = element.volume;
            var vad = element.vad;
            LogUtil.d('AgoraSDKUtil---> uid: ${uid}, volume: $volume, vad: $vad');
          });
          // LogUtil.d('AgoraSDKUtil---> speakers: ${speakers.toString()}, speakerNumber: $speakerNumber, totalVolume: $totalVolume');
          speakers.value = speakersTemp??[];

        },
      // 遇到错误
      onError: (ErrorCodeType err, String msg) {
        print('[onError] err: $err, msg: $msg');
        LogUtil.d("AgoraSDKUtil--->[onError] err: $err, msg: $msg");
      },
      onJoinChannelSuccess: (RtcConnection connection, int elapsed) {
        // 加入频道成功
        isJoined = true;
        LogUtil.d("AgoraSDKUtil--->加入频道成功，uid=${connection?.localUid}");
        LogUtil.d("AgoraSDKUtil--->加入频道成功，userId=${int.parse(UserParamsModel.instance.userId)}");
        update();
      },
      onUserJoined: (RtcConnection connection, int rUid, int elapsed) {
        // 有用户加入
        LogUtil.d("AgoraSDKUtil--->有用户加入，rUid=${rUid}");
        // remoteControllers[rUid] = VideoViewController.remote(
        //   rtcEngine: _engine,
        //   canvas: VideoCanvas(uid: rUid),
        //   connection: RtcConnection(channelId: '${roomInfo?.id}'),
        // );
        // update();
      },
      onUserOffline: (RtcConnection connection, int rUid, UserOfflineReasonType reason) {
        // 有用户离线
            LogUtil.d("AgoraSDKUtil--->有用户离线，rUid=${rUid}");
            // remoteControllers.remove(rUid);
            // update();
      },
      onLeaveChannel: (RtcConnection connection, RtcStats stats) {
        // 离开频道
        LogUtil.d("AgoraSDKUtil--->离开频道，localUid=${connection?.localUid}");
        isJoined = false;
        // remoteControllers.clear();
        update();
      },
    ));

    // // 打开视频模块支持
    // await _engine.enableVideo();
    // // 配置视频编码器，编码视频的尺寸（像素），帧率
    // await _engine.setVideoEncoderConfiguration(
    //   const VideoEncoderConfiguration(
    //     dimensions: VideoDimensions(width: 640, height: 360),
    //     frameRate: 15,
    //   ),
    // );
    // await _engine.startPreview();
    // 加入频道
    LogUtil.d('AgoraSDKUtil--->roomInfo?.agoraToken=${roomInfo?.agoraToken}');
    LogUtil.d('AgoraSDKUtil--->roomInfo?.id=${roomInfo?.id}');
    await _engine.joinChannel(
      token: roomInfo?.agoraToken,
      // token: token,
      channelId: '${roomInfo?.id}',
      // channelId: channelId,
      uid: int.parse(UserParamsModel.instance.userId),
      // uid: 0,
      options: ChannelMediaOptions(
        channelProfile: ChannelProfileType.channelProfileLiveBroadcasting,
        //当前用户为房主时clientRoleBroadcaster，其余为观众：clientRoleAudience，默认都为观众,未上麦
        // clientRoleType: isHasPermission()?ClientRoleType.clientRoleBroadcaster :ClientRoleType.clientRoleAudience,
        clientRoleType: ClientRoleType.clientRoleAudience,
      ),
    );
    await adjustPlaybackSignalVolume(100);
  }
  adjustVolume(){
    if(voiceListenOpen.value){
      adjustPlaybackSignalVolume(0);
    }else{
      adjustPlaybackSignalVolume(100);
    }
  }
  adjustPlaybackSignalVolume(int volume)async{
    await _engine?.adjustPlaybackSignalVolume(volume);
    if(volume==0){
      voiceListenOpen.value = false;
    }else{
      voiceListenOpen.value = true;
    }
  }
  //调整采集音量
  adjustSpeakVolume(){
    if(speakRecordOpen.value){
      adjustRecordingSignalVolume(0);
    }else{
      adjustRecordingSignalVolume(100);
    }
  }
  adjustRecordingSignalVolume(int volume)async{
    await _engine?.adjustRecordingSignalVolume(volume);
    if(volume==0){
      speakRecordOpen.value = false;
    }else{
      speakRecordOpen.value = true;
    }
  }

  //设置为主播
  setRoleBroadcaster()async{
    isOnMic=true;
    await _engine.setClientRole(role: ClientRoleType.clientRoleBroadcaster);
  }
  //设置为观众
  setRoleAudience()async{
    isOnMic=false;
    await _engine.setClientRole(role: ClientRoleType.clientRoleAudience);
  }

  // onItemViewTap(MapEntry<int, VideoViewController> e) {
  //   remoteControllers[e.key] = currentController;
  //   currentController = e.value;
  //   update();
  // }

  _setJoinRoomSuccess(){
    Map<String,dynamic> upData={
      'searchValue': roomInfo?.id,
    };
    moduleIndexService.api_voicechat_room_joinRoomSuccess(parmsMap: upData);
  }
  _setLinsener(){
    NimCore.instance.chatroomService.onMessageReceived
        .listen((List<NIMChatroomMessage> chatRoomMessages){
      LogUtil.d('NIMSDKUtil--->onChatroomServiceMessageReceivedListen');
      (chatRoomMessages??[]).forEach((element) {
        NIMMessageType messageType2 = element?.messageType;
        LogUtil.d('NIMSDKUtil--->notification messageType2=${messageType2}');
        if(NIMMessageType.notification == messageType2){
          var messageSubType = element?.messageSubType;
          NIMChatroomNotificationAttachment messageAttachment = element?.messageAttachment;
          LogUtil.d('NIMSDKUtil--->notification messageAttachment=${messageAttachment?.toMap()}');
          LogUtil.d('NIMSDKUtil--->notification messageAttachment type=${messageAttachment?.type}');
          // NIMChatroomNotificationAttachment
          //NIMChatroomMemberInAttachment
          switch (messageAttachment.type) {
            case NIMChatroomNotificationTypes.chatRoomMemberIn:
              // attachmentMemberMessage.value =
              attachmentMemberMessages.value.insert(0,MemberStatusEntity(
                fromAccount: element?.fromAccount,
                fromNickName: messageAttachment?.operatorNick,
                type: messageAttachment?.type,
              ));
              attachmentMemberMessages.refresh();
              // //将人员添加到集合，并去重
              // chatRoomMemberIds.add(element?.fromAccount);
              // //去重
              // Set<String> chatRoomMemberIdsSets = new Set();
              // chatRoomMemberIdsSets.addAll(chatRoomMemberIds);
              // chatRoomMemberIds = chatRoomMemberIdsSets.toList();
              // getMembers();
              if(!chatRoomServiceMembersAccIds.contains(element?.fromAccount)){
                chatRoomServiceMembersAccIds.add(element?.fromAccount);
                //获取服务端成员列表
                _getChatRoomServiceMembers();
              }
              //将此人添加到普通成员
              // addGuestToNormal(element?.fromAccount);
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberExit:
              attachmentMemberMessages.value.insert(0,MemberStatusEntity(
                fromAccount: element?.fromAccount,
                fromNickName: messageAttachment?.operatorNick,
                type: messageAttachment?.type,
              ));
              attachmentMemberMessages.refresh();
              // //将人员从集合中去除，并去重
              // chatRoomMemberIds.removeWhere((id)=>id==element?.fromAccount);
              // //去重
              // Set<String> chatRoomMemberIdsSets = new Set();
              // chatRoomMemberIdsSets.addAll(chatRoomMemberIds);
              // chatRoomMemberIds = chatRoomMemberIdsSets.toList();
              // // getMembers();
              if(!chatRoomServiceMembersAccIds.contains(element?.fromAccount)){
                chatRoomServiceMembersAccIds.add(element?.fromAccount);
                //获取服务端成员列表
                _getChatRoomServiceMembers();
              }
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberBlackAdd:
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberBlackRemove:
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberMuteAdd:
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberMuteRemove:
              break;
            case NIMChatroomNotificationTypes.chatRoomManagerAdd:
              break;
            case NIMChatroomNotificationTypes.chatRoomManagerRemove:
              break;
            case NIMChatroomNotificationTypes.chatRoomCommonAdd:
              break;
            case NIMChatroomNotificationTypes.chatRoomCommonRemove:
              break;
            case NIMChatroomNotificationTypes.chatRoomClose:
              attachmentMemberMessages.value.insert(0,MemberStatusEntity(
                fromAccount: element?.fromAccount,
                fromNickName: messageAttachment?.operatorNick,
                type: messageAttachment?.type,
              ));
              attachmentMemberMessages.refresh();
              if(!chatRoomServiceMembersAccIds.contains(element?.fromAccount)){
                chatRoomServiceMembersAccIds.add(element?.fromAccount);
                //获取服务端成员列表
                _getChatRoomServiceMembers();
              }
              break;
            case NIMChatroomNotificationTypes.chatRoomInfoUpdated:
              //更新房间信息
              getRommInfo();
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberKicked:
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberTempMuteAdd:
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberTempMuteRemove:
              break;
            case NIMChatroomNotificationTypes.chatRoomMyRoomRoleUpdated:
              break;
            case NIMChatroomNotificationTypes.chatRoomQueueChange:
              break;
            case NIMChatroomNotificationTypes.chatRoomRoomMuted:
              break;
            case NIMChatroomNotificationTypes.chatRoomRoomDeMuted:
              break;
            case NIMChatroomNotificationTypes.chatRoomQueueBatchChange:
              break;
            default:
              break;
          }
        }
        else if(NIMMessageType.custom == messageType2){
          // element.remoteExtension
          // NIMChatroomNotificationAttachment messageAttachment = element?.messageAttachment;
          LogUtil.d('NIMSDKUtil--->notification element=${element?.toMap()}');
          var remoteExtensions = element?.remoteExtension;
          if((remoteExtensions!=null)&&(remoteExtensions is Map)){
            var remoteExtensionDatas = remoteExtensions['data'];
            var extensionDatas = remoteExtensions['extension'];
            if((remoteExtensionDatas!=null)&&(remoteExtensionDatas is List)){
              if(remoteExtensionDatas.length>0){
                int idsPreLength = chatRoomServiceMembersAccIds.length;
                remoteExtensionDatas.forEach((remoteExte) {
                  if((remoteExte['giftImg']??'').isNotEmpty){
                    VoicePersonEntity toPersonTemp;
                    var toPersonTemps = (defaultPersons??[]).where((element) => ('${element?.userId}'== '${remoteExte['receiverUserId']}')).toList();
                    if(toPersonTemps.isNotEmpty)toPersonTemp = toPersonTemps[0];
                    LogUtil.d('remoteExtensions--->$remoteExtensions');
                    //针对送礼
                    attachmentMemberMessages.value.insert(0,MemberStatusEntity(
                      fromAccount: element?.fromAccount,
                      fromNickName: element?.fromNickname,
                      toAccount: toPersonTemp?.yxAccid,
                      toNickName: toPersonTemp?.nickname,
                      giftSmallImg: remoteExte['giftSmallImg'],
                      giftNum: remoteExte['giftNum'],
                      type: 600,
                    ));
                    attachmentMemberMessages.refresh();
                    if(!chatRoomServiceMembersAccIds.contains(element?.fromAccount)){
                      chatRoomServiceMembersAccIds.add(element?.fromAccount);
                    }
                    return;
                  }
                  //上麦位
                  defaultPersons.forEach((defaultPerson) {
                    if(remoteExte['mikeIndex'] == defaultPerson?.mikeIndex){
                      defaultPerson.lockFlag = remoteExte['lockFlag'];
                      defaultPerson.identityType = remoteExte['identityType'];
                      defaultPerson.icon = remoteExte['icon'];
                      defaultPerson.nickname = remoteExte['nickname'];
                      defaultPerson.userId = remoteExte['userId'];
                      defaultPerson.yxAccid = remoteExte['yxAccid'];
                      if(!chatRoomServiceMembersAccIds.contains(remoteExte['yxAccid'])){
                        chatRoomServiceMembersAccIds.add(remoteExte['yxAccid']);
                      }
                      //设置
                    }
                  });
                });
                if(idsPreLength!=chatRoomServiceMembersAccIds.length){
                  //获取服务端成员列表
                  _getChatRoomServiceMembers();
                }
                List<String> defaultPersonsAccs = defaultPersons.map((e) => e?.yxAccid).toList();
                if(isOnMic&&(!defaultPersonsAccs.contains(UserParamsModel.instance.yxAccid))){
                  //则下麦了
                  setRoleAudience();
                }
                update();
              }
            }
          }

        }
      });
      setChatRoomMessages(messages: chatRoomMessages??[]);
    });
    NimCore.instance.systemMessageService.onCustomNotification.listen((CustomNotification event) {
      LogUtil.d('NIMSDKUtil--->  inviteOnMic onCustomNotification--->event=${event?.toMap()}');
      if((event?.content??'').isNotEmpty){
        var contentTemp = json.decode(event?.content??'');
        if(contentTemp is Map){
          var notifyType = contentTemp['notifyType'];
          if(notifyType == 'invite_onmic'){
            //邀请上麦
            // {"attachType":-3,"notifyType":"invite_onmic","roomId":100,
            // "icon":"https://app-bucket-test.oss-accelerate.aliyuncs.com/ios/77985415/230305/u678994803_4000x3000_20230305194926.jpg",
            // "nickname":"lx","userId":1284,"yxAccid":"87118bd5619640f6a8c408533479d9a4"}
            var fromRoomId = contentTemp['roomId'];
            if(fromRoomId!=roomInfo?.id)return;
            var fromNickName = contentTemp['nickname'];
            var fromIcon = contentTemp['icon'];
            showDialog(
                context: Get.context,
                builder: (_){
                  return InviteOnMicGradientDialog(
                    message: '${fromNickName} ${StringUtil.instance.invites_you_to_on_mic}',
                    icon: fromIcon,
                    onPositivePressEvent: (){
                      Navigator.of(Get.context).pop();

                    },
                    onCloseEvent: (){
                      LogUtil.d('showDialog-->onCloseEvent');
                      Navigator.of(Get.context).pop();
                    },
                  );
                }
            );
          }else if(notifyType=='kickOut'){
            isForceLeave = true;
            ToastUtil.toast(StringUtil.instance.You_are_forced_to_leave_the_room);
            if(isUpWheat(currVoicePersonEntity)){
              var currPersions = defaultPersons.where((element) => (element?.userId==currVoicePersonEntity?.userId)).toList();
              LogUtil.d('离开事件通知---->currPersions.isNotEmpty=${currPersions.isNotEmpty},');
              if(currPersions.isNotEmpty)downMic(currPersions[0]);
            }
            logOutChatRoom();
            NavigatorUtil.goBack();
          }
        }
      }
    });
    NimCore.instance.chatroomService.onEventNotified.listen((NIMChatroomEvent event){
      LogUtil.d('NIMSDKUtil--->onChatroomServiceEventNotifiedListen');
      if (event is NIMChatroomStatusEvent) {
        /// 连接状态事件通知
      }else if (event is NIMChatroomKickOutEvent) {
        /// 离开事件通知
        // nimChatroomKickOutEvent.value = event;
        isForceLeave = true;
        NavigatorUtil.goBack();
        ToastUtil.toast(StringUtil.instance.You_are_forced_to_leave_the_room);
        // if(isUpWheat(currVoicePersonEntity)){
        //   var currPersions = defaultPersons.where((element) => (element?.userId==currVoicePersonEntity?.userId)).toList();
        //   if(currPersions.isNotEmpty)downMic(currPersions[0]);
        //   NavigatorUtil.goBack();
        //   logOutChatRoom();
        // }
      }
    });
    NimCore.instance.chatroomService.onMessageStatusChanged.listen((NIMChatroomMessage chatRoomMessage){
      LogUtil.d('NIMSDKUtil--->onChatroomServiceMessageStatusChangedListen');


    });
  }
  setChatRoomMessages({List<NIMChatroomMessage> messages,bool isInitData}) async {
    //更新消息列表
    if (messages.length > 0) {

      List<NIMChatroomMessage> successMessages = messages.where((element) =>
      element.status == NIMMessageStatus.success &&
          (element.messageType == NIMMessageType.image ||
              element.messageType == NIMMessageType.text)).toList();
      if(isInitData??false){
        chatRoomMsgs.value = [];
      }
      List<String> accountsTemp = (successMessages??[]).map((e) => e?.fromAccount).toList();
      accountsTemp.forEach((element) {
        if(!chatRoomServiceMembersAccIds.contains(element)){
          chatRoomServiceMembersAccIds.add(element);
        }
      });

      // chatRoomMemberIds.addAll(accountsTemp);
      // //去重
      // Set<String> chatRoomMemberIdsSets = new Set();
      // chatRoomMemberIdsSets.addAll(chatRoomMemberIds);
      // chatRoomMemberIds = chatRoomMemberIdsSets.toList();
      //获取成员
      getMembers();
      chatRoomMsgs.value.insertAll(0,successMessages);
      chatRoomMsgs.refresh();

    }
  }
  @override
  void onClose() {
    logOutChatRoom();
    // currentController.disposeRender();
    // currentController.dispose();
    if(_engine!=null)_engine.leaveChannel();
    if(_engine!=null)_engine.release();

    if(isUpWheat(currVoicePersonEntity)){
      var currPersions = defaultPersons.where((element) => (element?.userId==currVoicePersonEntity?.userId)).toList();
      if(currPersions.isNotEmpty&&(!isForceLeave))downMic(currPersions[0]);
    }
    super.onClose();
  }

  onCommentTap() async {
    // LogUtil.d('-------------->onCommentTap isCommentOpen=${isCommentOpen.value}');
    // isCommentOpen.value = true;
    // await Future.delayed(Duration(milliseconds: 100));
    // LogUtil.d('-------------->onCommentTap hasFocus=${commitFocusNode.hasFocus}');

    showModalBottomSheet(
        context: Get.context,
        isScrollControlled: true,
        builder: (BuildContext context){
          return SendCommentWidget(
            sendMsgFunc: (comments){
              LogUtil.d('发送消息');
              if((comments??'').isEmpty){
                ToastUtil.toast(StringUtil.instance.Please_input_your_idea);
                return;
              }
              NavigatorUtil.goBack();
              sendMsg(comments);
            },
          );
        }
    );
  }

  /**
   * 发送消息
   */
  sendMsg(comments) async{
    // isCommentOpen.value = false;
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.Send}...');
    NIMResult<NIMChatroomMessage> createMsgResult = await NIMSDKUtil.instance.createChatroomTextMessage(
        roomId: roomInfo?.yxRoomId,text: comments);
    if(!(createMsgResult?.isSuccess??false)){
      LoadUtil.hideLoad();
      ToastUtil.toast(StringUtil.instance.Send_fail);
      return;
    }
    NIMResult<NIMChatroomMessage> sendMsgResult = await NIMSDKUtil.instance.sendChatroomMessage(
      message: createMsgResult?.data,
    );
    LoadUtil.hideLoad();
    if(sendMsgResult?.isSuccess??false){
      ToastUtil.toast(StringUtil.instance.Send_success);
      chatRoomMsgs.value.insert(0,sendMsgResult.data);
      chatRoomMsgs.refresh();
      if(!chatRoomServiceMembersAccIds.contains(sendMsgResult?.data?.fromAccount)){
        chatRoomServiceMembersAccIds.add(sendMsgResult?.data?.fromAccount);
        //获取服务端成员列表
        _getChatRoomServiceMembers();
      }
    }else{
      ToastUtil.toast(StringUtil.instance.Send_fail);
    }
  }

  void _fetchMessageHistory() async {
    NIMResult<List<NIMChatroomMessage>> historyMessages =
        await NIMSDKUtil.instance.fetchMessageHistory(
      roomId: roomInfo?.yxRoomId,
    );
    if(historyMessages?.isSuccess){
      setChatRoomMessages(messages: (historyMessages?.data??[]),isInitData: true);
    }
  }
  getRommInfo(){
    _getRommYxInfo();
    _getRoomInfoByRoomCode();
  }
  void _getRommYxInfo() async {
    NIMResult<NIMChatroomInfo> roomInfoResult =
        await NIMSDKUtil.instance.fetchChatroomInfo(
      roomId: roomInfo?.yxRoomId,
    );
    if(roomInfoResult?.isSuccess){
      roomYxInfo.value = roomInfoResult?.data;
      LogUtil.d('roomInfo--->${roomYxInfo.value.extension}');
      LogUtil.d('roomInfo--->roomId=${roomYxInfo.value.roomId}');
      getMembers();
    }
  }
  void _getRoomInfoByRoomCode() async{
    // api_voicechat_room_queryRoomByCode
    BaseEntity baseEntity = await moduleIndexService.api_voicechat_room_queryRoomByCode(parmsMap: {
      'searchValue': roomInfo?.roomCode
    });
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      IndexRoomItemEntity results = baseEntity.result;
      LogUtil.d('results--->${results?.toJson()}');
      if(results!=null){
        roomInfo.roomName = results.roomName;
        roomInfo.roomSynopsis = results.roomSynopsis;
        roomInfo.password = results.password;
        roomInfo.charismaShow = results.charismaShow;
        roomInfo.charisma = results.charisma;
        roomInfo.coverImg = results.coverImg;
        update();
      }
    }
  }

  void logOutChatRoom() async{
    var nimResult = await NIMSDKUtil.instance.exitChatroom(roomId: roomInfo?.yxRoomId);
    if(nimResult?.isSuccess){
      LogUtil.d('NIMSDKUtil--->退出聊天室成功');
    }
  }

  /**
   * 获取房间成员
   */
  void getMembers() async{
    // LogUtil.d('NIMSDKUtil,getMembers chatRoomMemberIds =${chatRoomMemberIds}');
    // NIMResult<List<NIMChatroomMember>> membersResult = await NIMSDKUtil.instance
    //     .fetchChatroomMembersByAccounts(myRoom?.yxRoomId, chatRoomMemberIds);

    // NIMResult<List<NIMChatroomMember>> membersResult = await NimCore.instance.chatroomService.fetchChatroomMembersByAccount(
    //   roomId: myRoom?.yxRoomId,
    //   accountList: chatRoomMemberIds,
    // );

    List<NIMChatroomMember> membersResult = await NIMSDKUtil.instance
        .fetchChatroomMembers(roomInfo?.yxRoomId,1000000);
    LogUtil.d('NIMSDKUtil,getMembers isSuccess =${membersResult}');
    var membersLists = membersResult??[];
    LogUtil.d('NIMSDKUtil,getMembers membersLists =${membersLists.length}');
    if(membersLists.isNotEmpty){
      int idsPreLength = chatRoomServiceMembersAccIds.length;
      membersLists.forEach((element) {
        if(!chatRoomServiceMembersAccIds.contains(element?.account)){
          chatRoomServiceMembersAccIds.add(element?.account);
        }
      });
      if(idsPreLength!=chatRoomServiceMembersAccIds.length){
        //获取服务端成员列表
        _getChatRoomServiceMembers();
      }
      //
      // List<String> accounts = chatRoomMembers.map((e) => e?.account).toList();
      // //将人员添加到集合，并去重
      // roomTotalAccounts.addAll(accounts);
      // //去重
      // Set<String> roomTotalAccountsSets = new Set();
      // roomTotalAccountsSets.addAll(roomTotalAccounts);
      // roomTotalAccounts = roomTotalAccountsSets.toList();
      // int idsPreLength = chatRoomServiceMembersAccIds.length;
      // membersLists.forEach((element) {
      //   if(!chatRoomServiceMembersAccIds.contains(element?.account)){
      //     chatRoomServiceMembersAccIds.add(element?.account);
      //   }
      // });
      // if(idsPreLength!=chatRoomServiceMembersAccIds.length){
      //   //获取服务端成员列表
      //   _getChatRoomServiceMembers();
      // }
      // chatRoomMembers.clear();
      // chatRoomMembers.addAll(membersLists);
      // update();
    }
  }
  //获取服务端成员列表
  void _getChatRoomServiceMembers() async{
    // List<String> yxMembersIds = (chatRoomMembers??[]).map((e) => e?.account).toList();
    //if(!chatRoomServiceMembersAccIds.contains(element?.account)){
    //           chatRoomServiceMembersAccIds.add(element?.account);
    //         }

    if(chatRoomServiceMembersAccIds.isEmpty)return;
    Map<String,dynamic> upData={
      "roomId": roomInfo?.id,
      // "yxAccids": roomTotalAccounts
      "yxAccids": chatRoomServiceMembersAccIds
    };
    LogUtil.d('_getChatRoomServiceMembers--->chatRoomServiceMembersAccIds=$chatRoomServiceMembersAccIds');
    BaseEntity baseEntity= await moduleIndexService
        .api_voicechat_room_queryOnlineUserInfo(parmsMap: upData);
    if(baseEntity?.code==ApiConfig.SUCCESS_CODE){
      List<UserEntity> dataTemps=baseEntity?.result??[];
      if(dataTemps.isNotEmpty){
        chatRoomServiceMembers.clear();
        chatRoomServiceMembers.addAll(dataTemps);
        update();
      }
    }
  }


  toRoomSet() {
    NavigatorUtil.pushByName(RouteConfig.roomSetPage,arguments: {
      'roomInfo':roomInfo,
      'roomYxInfo':roomYxInfo.value
    });
  }
  toRoomClose(){
    showDialog(
        context: Get.context,
        builder: (BuildContext context){
          return RoomTopWidget(
            onRoomClose: (){
              LogUtil.d('退出房间');
              NavigatorUtil.goBack();
              NavigatorUtil.goBack();
            },
          );
        }
    );
  }

  AudioVolumeInfo getCurrAgoraPerson(VoicePersonEntity voicePerson) {
    LogUtil.d('getCurrAgoraPerson-->userId=${voicePerson?.userId}');
    LogUtil.d('getCurrAgoraPerson-->speakers.value=${speakers.value?.map((e) => e?.toJson())?.toList()}');
    List<AudioVolumeInfo> speakersTemp = (speakers.value??[]).where((element) =>
    (element?.uid==voicePerson?.userId)||
    (element?.uid==0)
    ).toList();
    if(speakersTemp.isNotEmpty)return speakersTemp[0];
    return null;
  }

  //查询此用户和此房间的关系
  void queryUserRoomRelationType() async{
    Map<String,dynamic> upData={
      "roomId": roomInfo?.id,
      "userId": UserParamsModel.instance.userId
    };
    BaseEntity baseEntity = await moduleIndexService.
    api_voicechat_room_queryUserRoomRelationType(parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      currVoicePersonEntity = baseEntity?.result??VoicePersonEntity();
      LogUtil.d('queryUserRoomRelationType-->currVoicePersonEntity=${currVoicePersonEntity?.toJson()}');
      // if(voicePersonEntity?.userId == roomInfo?.homeownerId){
      //   voicePersonEntity.isUpWheat = true;
      //   voicePersonEntity.isCloseWheat = false;
      // }
      update();
    }else{
      //组合为观众
      currVoicePersonEntity = VoicePersonEntity(
        userId: int.parse(UserParamsModel.instance.userId),
        icon: UserParamsModel.instance.userEntity?.icon,
        yxAccid: UserParamsModel.instance.yxAccid,
        nickname: UserParamsModel.instance.userEntity?.nickname,
      );
    }
    update();
  }
  //
  // void getPersonByUserId(int userId,int mikeIndex) async{
  //   Map<String,dynamic> upData={
  //     "roomId": roomInfo?.id,
  //     "userId": userId
  //   };
  //   BaseEntity baseEntity = await moduleIndexService.
  //   api_voicechat_room_queryUserRoomRelationType(parmsMap: upData);
  //   if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
  //     var voicePersonEntity = baseEntity?.result??VoicePersonEntity();
  //     defaultPersons[mikeIndex]=voicePersonEntity;
  //     // if(mikeIndex==0)defaultPersons[mikeIndex].isUpWheat = true;
  //     // if(mikeIndex==0)defaultPersons[mikeIndex].isCloseWheat = false;
  //     update();
  //   }
  // }
  //用户是否上麦
  bool isUpWheat(VoicePersonEntity voicePersonTemp) {
    return defaultPersons.where((element) => (
        (element.yxAccid??'').isNotEmpty&&(element?.userId==voicePersonTemp?.userId)
    )).isNotEmpty;
  }
  //用户是否闭麦
  bool isSpeakRecordOpen() {
    return speakRecordOpen.value;
  }
  //当前用户是否被禁言
  bool isSelfLimitedSpeak() {
     List<VoicePersonEntity> upSelfPersons = (defaultPersons??[]).where((element) => (
        (element.yxAccid??'').isNotEmpty&&(element?.userId==currVoicePersonEntity?.userId)
    )).toList();
    if(upSelfPersons.isEmpty)return true;
     VoicePersonEntity upSelfPerson = upSelfPersons[0];
     if('${upSelfPerson?.relationType}'=='6')return true;
    return false;
  }

  //是否是自己
  bool isMySelf(int userId,int destUserId) {
    if(userId==null||destUserId==null)return false;
    return userId == destUserId;
  }
  //关系类型:2:管理员,3:主播,4:黑名单,6:禁言
  bool isRoomCreatorOrAdmin(int relationType){
    return ('$relationType' == '1')
        ||('$relationType' == '2')
    ;
  }
  //关系类型:2:管理员,3:主播,4:黑名单,6:禁言
  bool isRoomCreator(dynamic relationType){
    LogUtil.d('isRoomCreator--->${('$relationType' == '1')},relationType=$relationType');
    return ('$relationType' == '1');
  }
  //点击上麦用户麦位
  onUpWheatPersonPositionTap(int index, VoicePersonEntity voicePerson) {
    if(isMySelf(currVoicePersonEntity?.userId,voicePerson?.userId)){
      //点击自己、弹出个人信息，且可以下麦
      showDialog(
          context: Get.context,
          builder: (_){
            return RoomSelfInfoGradientDialog(
              icon: voicePerson?.icon,
              name: voicePerson?.nickname,
              vipFlag: voicePerson?.vipFlag,
              userId: voicePerson?.userId,
              isUpMick: isUpWheat(voicePerson),
              dowmMickTap: (){
                LogUtil.d('点击下麦');
                NavigatorUtil.goBack();
                //调用下麦接口
                downMic(voicePerson);
              },
              toHomeTap: (){
                LogUtil.d('点击去人员首页');
                toPersonHome(voicePerson);
              },
            );
          }
      );
    }else{
      //如果是房主或管理员，点击其他人，弹出下麦、禁言、拉黑、设置为管理员、踢出房间操作，其中房主身份才能设置管理员
      if(isRoomCreatorOrAdmin(currVoicePersonEntity?.relationType)){
        showDialog(
            context: Get.context,
            builder: (_){
              return RoomOtherInfoGradientDialog(
                icon: voicePerson?.icon,
                name: voicePerson?.nickname,
                vipFlag: voicePerson?.vipFlag,
                userId: voicePerson?.userId,
                isUpMick: isUpWheat(voicePerson),
                isForbidden: isCloseWheat(voicePerson),
                isFollow: isFollow(voicePerson),
                followTap: (){LogUtil.d('点击关注');NavigatorUtil.goBack();toFollowPerson(voicePerson);},
                chatTap: (){LogUtil.d('点击聊天');NavigatorUtil.goBack();toChat(voicePerson);},
                toHomeTap: (){LogUtil.d('点击去人员首页');toPersonHome(voicePerson);},
                giftsTap: (){LogUtil.d('点击礼物');NavigatorUtil.goBack();onOpenGifts(defaultPersons: [UserEntity(
                    userId: voicePerson?.userId,
                    nickname: voicePerson?.nickname,
                    icon: voicePerson?.icon,
                  yxAccid: voicePerson?.yxAccid
                )]);},
                mickTap: (){LogUtil.d('点击下麦');NavigatorUtil.goBack();downMic(voicePerson);},
                voiceTap: (){LogUtil.d('点击麦克风');NavigatorUtil.goBack();forbiddenPerson(voicePerson);},
                blacklistTap: (){LogUtil.d('点击拉黑');NavigatorUtil.goBack();blockPerson(voicePerson);},
                adminTap: (){LogUtil.d('点击管理员');NavigatorUtil.goBack();setAdminPerson(voicePerson);},
                kickoutTap: (){LogUtil.d('点击踢出房间');NavigatorUtil.goBack();kickOutPerson(voicePerson);},
              );
            }
        );
      }
      //如果是其他身份，点击其他人，则无操作
    }
  }
  //点击未上麦麦位
  onUnUpWheatPersonPositionTap(int index, VoicePersonEntity voicePerson) {
    if(isRoomCreatorOrAdmin(currVoicePersonEntity?.relationType)){
      if(voicePerson?.lockFlag==1){
        //已经锁麦，弹出解锁麦、解锁所有锁定的麦
        popUnLockFlagOper(voicePerson);
      }else{
        //当前房主或管理员，若当前人员为房主且未上麦，弹出上麦，锁麦、锁所有未上麦的麦位
        popLockFlagOper(voicePerson);
      }
    }else{
      //当前观众，判断是否锁麦，锁麦则直接返回；未锁麦则直接上麦
      if(voicePerson?.lockFlag==1)return;
      if(isUpWheat(currVoicePersonEntity))return;
      //调用上麦接口
      upMic(voicePerson);
    }
  }

  onSpeekPersonPositionTap(int index, UserEntity user) {
    LogUtil.d('onSpeekPersonPositionTap-->user=${user?.toJson()}');
    // NIMSDKUtil.instance.markChatroomMemberInBlackList(
    //     isAdd: false,
    //     roomId: roomYxInfo.value.roomId,
    //     account: 'd57c138c56fa4c42aac34e6d606edfb8'
    // );
    // return;
    List<UserEntity> chatRoomServiceMemberTemps = (chatRoomServiceMembers??[]).where((element) => (element?.yxAccid==user?.yxAccid)).toList();
    UserEntity chatRoomServiceMember =  UserEntity();
    if(chatRoomServiceMemberTemps.isNotEmpty)chatRoomServiceMember = chatRoomServiceMemberTemps[0];
    VoicePersonEntity micMember = VoicePersonEntity(
        userId: chatRoomServiceMember?.userId,
        icon: chatRoomServiceMember?.icon,
        yxAccid: chatRoomServiceMember?.yxAccid,
        nickname: chatRoomServiceMember?.nickname,
        vipFlag: chatRoomServiceMember?.vip,
    );

    List<VoicePersonEntity> micMemberTemps = (defaultPersons??[]).where((element) => (element?.yxAccid==user?.yxAccid)).toList();
    if(micMemberTemps.length>0){
      //已上麦
      micMember = micMemberTemps[0];
    }else{
      //没有上麦
    }

    if(isRoomCreatorOrAdmin(currVoicePersonEntity?.relationType)){
      //当前操作人为房主或管理员
      if(isRoomCreator(currVoicePersonEntity?.relationType)){
        //若操作人为房主
        if(isMySelf(currVoicePersonEntity?.userId,micMember?.userId)){
          //判断被操作人为房主,判断是否上麦，若上麦可以下麦
          //点击自己、弹出个人信息，且可以下麦
          if(!isUpWheat(micMember))return;
          showDialog(
              context: Get.context,
              builder: (_){
                return RoomSelfInfoGradientDialog(
                  icon: micMember?.icon,
                  name: micMember?.nickname,
                  vipFlag: micMember?.vipFlag,
                  userId: micMember?.userId,
                  isUpMick: isUpWheat(micMember),
                  dowmMickTap: (){
                    LogUtil.d('点击下麦');
                    NavigatorUtil.goBack();
                    downMic(micMember);
                  },
                  toHomeTap: (){
                    LogUtil.d('点击去人员首页');
                    toPersonHome(micMember);
                  },
                );
              }
          );
        }else{
          //判断被操作人其他人，点击其他人，弹出下麦、禁言、拉黑、设置为管理员、踢出房间操作，其中房主身份才能设置管理员
          //查询是否还在房间
          if(!(chatRoomServiceMembers.map((e) => e?.yxAccid)).contains(micMember.yxAccid))return;
          showDialog(
              context: Get.context,
              builder: (_){
                return RoomOtherInfoGradientDialog(
                  icon: micMember?.icon,
                  name: micMember?.nickname,
                  vipFlag: micMember?.vipFlag,
                  userId: micMember?.userId,
                  isUpMick: isUpWheat(micMember),
                  isForbidden: isCloseWheat(micMember),
                  isFollow: isFollow(micMember),
                  followTap: (){LogUtil.d('点击关注');NavigatorUtil.goBack();toFollowPerson(micMember);},
                  chatTap: (){LogUtil.d('点击聊天');NavigatorUtil.goBack();toChat(micMember);},
                  toHomeTap: (){LogUtil.d('点击去人员首页');toPersonHome(micMember);},
                  giftsTap: (){LogUtil.d('点击礼物');NavigatorUtil.goBack();onOpenGifts(defaultPersons: [chatRoomServiceMember]);},
                  mickTap: (){
                    LogUtil.d('点击上下麦');
                    NavigatorUtil.goBack();
                    if(isUpWheat(micMember)){
                      //进行下麦操作
                      downMic(micMember);
                    }else{
                      //邀请上麦
                      inviteOnMic(micMember);
                    }
                  },
                  voiceTap: (){LogUtil.d('点击麦克风');NavigatorUtil.goBack();forbiddenPerson(micMember);},
                  blacklistTap: (){LogUtil.d('点击拉黑');NavigatorUtil.goBack();blockPerson(micMember);},
                  adminTap: (){LogUtil.d('点击管理员');NavigatorUtil.goBack();setAdminPerson(micMember);},
                  kickoutTap: (){LogUtil.d('点击踢出房间');NavigatorUtil.goBack();kickOutPerson(micMember);},
                );
              }
          );
        }
      }else{
        //当前操作人为管理员
        //被操作人为创建者
        if(isRoomCreator(micMember?.identityType))return;
        if(isMySelf(currVoicePersonEntity?.userId,micMember?.userId)){
          //点击自己、弹出个人信息，且可以下麦
          if(!isUpWheat(micMember))return;
          showDialog(
              context: Get.context,
              builder: (_){
                return RoomSelfInfoGradientDialog(
                  icon: micMember?.icon,
                  name: micMember?.nickname,
                  vipFlag: micMember?.vipFlag,
                  userId: micMember?.userId,
                  isUpMick: isUpWheat(micMember),
                  dowmMickTap: (){
                    LogUtil.d('点击下麦');
                    NavigatorUtil.goBack();
                    downMic(micMember);
                  },
                  toHomeTap: (){
                    LogUtil.d('点击去人员首页');
                    toPersonHome(micMember);
                  },
                );
              }
          );
        }else{
          //点击的观众，弹出下麦、禁言、拉黑、设置为管理员、踢出房间操作，其中房主身份才能设置管理员
          //查询是否还在房间
          if(!(chatRoomServiceMembers.map((e) => e?.yxAccid)).contains(micMember.yxAccid))return;
          showDialog(
              context: Get.context,
              builder: (_){
                return RoomOtherInfoGradientDialog(
                  icon: micMember?.icon,
                  name: micMember?.nickname,
                  vipFlag: micMember?.vipFlag,
                  userId: micMember?.userId,
                  isUpMick: isUpWheat(micMember),
                  isForbidden: isCloseWheat(micMember),
                  isFollow: isFollow(micMember),
                  followTap: (){LogUtil.d('点击关注');NavigatorUtil.goBack();toFollowPerson(micMember);},
                  chatTap: (){LogUtil.d('点击聊天');NavigatorUtil.goBack();toChat(micMember);},
                  toHomeTap: (){LogUtil.d('点击去人员首页');toPersonHome(micMember);},
                  giftsTap: (){LogUtil.d('点击礼物');NavigatorUtil.goBack();onOpenGifts(defaultPersons: [chatRoomServiceMember]);},
                  mickTap: (){
                    LogUtil.d('点击上下麦');
                    NavigatorUtil.goBack();
                    if(isUpWheat(micMember)){
                      //进行下麦操作
                      downMic(micMember);
                    }else{
                      //邀请上麦
                      inviteOnMic(micMember);
                    }
                  },
                  voiceTap: (){LogUtil.d('点击麦克风');NavigatorUtil.goBack();forbiddenPerson(micMember);},
                  blacklistTap: (){
                    LogUtil.d('点击拉黑');
                    NavigatorUtil.goBack();
                    blockPerson(micMember);},
                  adminTap: (){LogUtil.d('点击管理员');NavigatorUtil.goBack();setAdminPerson(micMember);},
                  kickoutTap: (){LogUtil.d('点击踢出房间');NavigatorUtil.goBack();kickOutPerson(micMember);},
                );
              }
          );
        }
      }
    }else{
      //当前为观众，不做任何操作
      LogUtil.d('isMySelf--->currVoicePersonEntity=${currVoicePersonEntity?.toJson()}');
      LogUtil.d('isMySelf--->currUserId=${currVoicePersonEntity?.userId},userId=${micMember?.userId}');
      if(isMySelf(currVoicePersonEntity?.userId,micMember?.userId)){
        //点击自己、弹出个人信息，且可以下麦
        if(!(isUpWheat(micMember)))return;
        showDialog(
            context: Get.context,
            builder: (_){
              return RoomSelfInfoGradientDialog(
                icon: micMember?.icon,
                name: micMember?.nickname,
                vipFlag: micMember?.vipFlag,
                userId: micMember?.userId,
                isUpMick: isUpWheat(micMember),
                dowmMickTap: (){
                  LogUtil.d('点击下麦');
                  NavigatorUtil.goBack();
                  downMic(micMember);
                },
                toHomeTap: (){
                  LogUtil.d('点击去人员首页');
                  toPersonHome(micMember);
                },
              );
            }
        );
      }
    }
  }

  //已经锁麦，弹出解锁麦、解锁所有锁定的麦
  popUnLockFlagOper(VoicePersonEntity voicePerson) {
    var operDatas = [StringUtil.instance.Unlock,StringUtil.instance.Unlock_all,];
    showDialog(
        context: Get.context,
        builder: (_){
          return CommSelectGradientDialog(
            datas: operDatas,
            initIndex: -1,
            onPositivePressEvent: (int index){
              LogUtil.d('showDialog-->onPositivePressEvent--->index=$index');
              Navigator.of(Get.context).pop();
              if(operDatas[index]== StringUtil.instance.Unlock){
                if(!(voicePerson?.lockFlag==1))return;
                //解锁
                unLockMic(voicePerson);
              }else if(operDatas[index]== StringUtil.instance.Unlock_all){
                //解锁所有麦
              }
            },
            onCloseEvent: (){
              LogUtil.d('showDialog-->onCloseEvent');
              Navigator.of(Get.context).pop();
            },
          );
        }
    );
  }
  //当前房主或管理员，若当前人员为房主且未上麦，弹出上麦，锁麦、锁所有未上麦的麦位
  popLockFlagOper(VoicePersonEntity voicePerson) {
    var operDatas = [StringUtil.instance.Lock_the_Mic,StringUtil.instance.Lock_all_Mic,];
    if(!isUpWheat(currVoicePersonEntity))operDatas.insert(0, StringUtil.instance.Take_the_Mic);
    showDialog(
        context: Get.context,
        builder: (_){
          return CommSelectGradientDialog(
            datas: operDatas,
            initIndex: -1,
            onPositivePressEvent: (int index){
              LogUtil.d('showDialog-->onPositivePressEvent--->index=$index');
              Navigator.of(Get.context).pop();
              if(operDatas[index]== StringUtil.instance.Lock_the_Mic){
                if(voicePerson?.lockFlag==1)return;
                //锁麦
                lockMic(voicePerson);
              }else if(operDatas[index]== StringUtil.instance.Lock_all_Mic){
                //锁所有待锁的麦
              }else if(operDatas[index]== StringUtil.instance.Take_the_Mic){
                //上麦
                if(isUpWheat(currVoicePersonEntity))return;
                upMic(voicePerson);
              }
            },
            onCloseEvent: (){
              LogUtil.d('showDialog-->onCloseEvent');
              Navigator.of(Get.context).pop();
            },
          );
        }
    );
  }

  void lockMic(VoicePersonEntity voicePerson) async{
    LoadUtil.showLoad(loadingText: StringUtil.instance.Locking);
    Map<String,dynamic> upData={
      "roomId": roomInfo?.id,
      "mikeIndex": voicePerson?.mikeIndex
    };
    BaseEntity baseEntity = await moduleIndexService.
    api_voicechat_room_lockMike(parmsMap: upData);
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      voicePerson.lockFlag = 1;
      update();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }
  void unLockMic(VoicePersonEntity voicePerson) async{
    LoadUtil.showLoad(loadingText: StringUtil.instance.Unlocking);
    Map<String,dynamic> upData={
      "roomId": roomInfo?.id,
      "mikeIndex": voicePerson?.mikeIndex
    };
    BaseEntity baseEntity = await moduleIndexService.
    api_voicechat_room_unlockMike(parmsMap: upData);
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      voicePerson.lockFlag = 0;
      update();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  void upMic(VoicePersonEntity voicePerson) async{
    LoadUtil.showLoad(loadingText: StringUtil.instance.Onmicing);
    Map<String,dynamic> upData={
      "roomId": roomInfo?.id,
      "mikeIndex": voicePerson?.mikeIndex
    };
    BaseEntity baseEntity = await moduleIndexService.
    api_voicechat_room_onMike(parmsMap: upData);
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      //设置为主播
      setRoleBroadcaster();
      update();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }
  void downMic(VoicePersonEntity voicePerson) async{
    LoadUtil.showLoad(loadingText: StringUtil.instance.Downmicing);
    Map<String,dynamic> upData={
      "roomId": roomInfo?.id,
      "mikeIndex": voicePerson?.mikeIndex
    };
    BaseEntity baseEntity = await moduleIndexService.
    api_voicechat_room_downMike(parmsMap: upData);
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      update();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  void inviteOnMic(VoicePersonEntity micMember) async{
    LogUtil.d('邀请上麦----->yxAccid=${micMember?.yxAccid}');
    var dict = {"attachType":-3,"notifyType":"invite_onmic","roomId": roomInfo?.id,"icon": currVoicePersonEntity?.icon,
      "nickname":currVoicePersonEntity?.nickname,"userId":currVoicePersonEntity?.userId,
      "yxAccid":currVoicePersonEntity?.yxAccid};
    // 配置 CustomNotificationConfig
    CustomNotificationConfig config = CustomNotificationConfig(enablePush:true,enableUnreadCount:true);
// 构造自定义通知，指定接收者
    CustomNotification notification = CustomNotification(sessionId: micMember?.yxAccid,
        sessionType:NIMSessionType.p2p,content: json.encode(dict),
        apnsText:"the_content_for_apns",config:config);
// 发送自定义通知
    NIMResult<void> result = await NimCore.instance.systemMessageService
        .sendCustomNotification(notification);
    if(result.isSuccess){
      ToastUtil.toast(StringUtil.instance.Send_success);
    }
    LogUtil.d('inviteOnMic--->result=${result?.toMap()}');
  }

  //点击去人员首页
  void toPersonHome(VoicePersonEntity voicePerson) {
    NavigatorUtil.pushByName(RouteConfig.otherPersonHomePage,arguments: {
      'userId': '${voicePerson?.userId}'
    });
  }

  //去移除，并且只有创建者可以对管理员进行操作，管理员不能对创建者和其他管理员进行操作。
  blockPerson(VoicePersonEntity voicePerson){
    //Add {username} to the blacklist, and the user will be forced to leave the room
    showDialog(
        context: Get.context,
        builder: (_){
          return CommMessageGradientDialog(
            message: '${StringUtil.instance.Revoke} ${voicePerson?.nickname} ${StringUtil.instance.to_the_blocklist_point}?',
            onPositivePressEvent: (){
              LogUtil.d('showDialog-->onPositivePressEvent');
              Navigator.of(Get.context).pop();
              startBlockPerson(voicePerson);
            },
            onCloseEvent: (){
              LogUtil.d('showDialog-->onCloseEvent');
              Navigator.of(Get.context).pop();
            },
          );
        }
    );
  }

  startBlockPerson(VoicePersonEntity voicePerson) async{
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    //关系类型:2:管理员,3:主播,4:黑名单,6:禁言
    Map<String,dynamic> upData={
      "relationType": 4,
      "roomId": roomInfo?.id,
      "userId": voicePerson?.userId
    };
    LogUtil.d('toMyRoom--->upData=$upData');
    LoadUtil.hideLoad();
    BaseEntity baseEntity = await moduleIndexService.
    api_voicechat_room_bindOrUnBindUserRoomRelation(parmsMap: upData,isBind: true);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      await NIMSDKUtil.instance.markChatroomMemberInBlackList(
          isAdd: true,
          roomId: roomYxInfo.value.roomId,
          account: voicePerson?.yxAccid
      );
      update();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  void setAdminPerson(VoicePersonEntity voicePerson) {
    //Set {username} as Administrator？
    showDialog(
        context: Get.context,
        builder: (_){
          return CommMessageGradientDialog(
            message: '${StringUtil.instance.Set} ${voicePerson?.nickname} ${StringUtil.instance.as_Administrator}?',
            onPositivePressEvent: (){
              LogUtil.d('showDialog-->onPositivePressEvent');
              Navigator.of(Get.context).pop();
              startSetAdminPerson(voicePerson);
            },
            onCloseEvent: (){
              LogUtil.d('showDialog-->onCloseEvent');
              Navigator.of(Get.context).pop();
            },
          );
        }
    );
  }
  startSetAdminPerson(VoicePersonEntity voicePerson) async{
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    //关系类型:2:管理员,3:主播,4:黑名单,6:禁言
    Map<String,dynamic> upData={
      "relationType": 2,
      "roomId": roomInfo?.id,
      "userId": voicePerson?.userId
    };
    LogUtil.d('toMyRoom--->upData=$upData');
    LoadUtil.hideLoad();
    BaseEntity baseEntity = await moduleIndexService.
    api_voicechat_room_bindOrUnBindUserRoomRelation(parmsMap: upData,isBind: true);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      await NIMSDKUtil.instance.markChatroomMemberBeManager(
          isAdd: true,
          roomId: roomYxInfo.value.roomId,
          account: voicePerson?.yxAccid
      );
      update();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  void kickOutPerson(VoicePersonEntity voicePerson) {
    //kickOut the user from the room
    showDialog(
        context: Get.context,
        builder: (_){
          return CommMessageGradientDialog(
            message: '${StringUtil.instance.kickOut_the} ${voicePerson?.nickname} ${StringUtil.instance.from_the_room}?',
            onPositivePressEvent: (){
              LogUtil.d('showDialog-->onPositivePressEvent');
              Navigator.of(Get.context).pop();
              startKickOutPerson(voicePerson);
            },
            onCloseEvent: (){
              LogUtil.d('showDialog-->onCloseEvent');
              Navigator.of(Get.context).pop();
            },
          );
        }
    );
  }
  startKickOutPerson(VoicePersonEntity voicePerson) async{
    LogUtil.d('邀请上麦----->yxAccid=${voicePerson?.yxAccid}');
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.Sending}...');
    var dict = {"attachType":-4,"notifyType":"kickOut","roomId": roomInfo?.id,"icon": currVoicePersonEntity?.icon,
      "nickname":currVoicePersonEntity?.nickname,"userId":currVoicePersonEntity?.userId,
      "yxAccid":currVoicePersonEntity?.yxAccid};
    // 配置 CustomNotificationConfig
    CustomNotificationConfig config = CustomNotificationConfig(enablePush:true,enableUnreadCount:true);
// 构造自定义通知，指定接收者
    CustomNotification notification = CustomNotification(sessionId: voicePerson?.yxAccid,
        sessionType:NIMSessionType.p2p,content: json.encode(dict),
        apnsText:"the_content_for_apns",config:config);
// 发送自定义通知
    NIMResult<void> result = await NimCore.instance.systemMessageService
        .sendCustomNotification(notification);
    LoadUtil.hideLoad();
    if(result.isSuccess){
      ToastUtil.toast(StringUtil.instance.Send_success);
    }
  }

  void forbiddenPerson(VoicePersonEntity voicePerson) {
    if(!isRoomCreatorOrAdmin(currVoicePersonEntity?.relationType))return;
    showDialog(
        context: Get.context,
        builder: (_){
          return CommMessageGradientDialog(
            message: '${(isCloseWheat(voicePerson))?StringUtil.instance.Revoke:StringUtil.instance.Add} ${voicePerson?.nickname} ${(isCloseWheat(voicePerson))?StringUtil.instance.from_the_forbiddenList:StringUtil.instance.to_the_forbiddenList}?',
            onPositivePressEvent: (){
              LogUtil.d('showDialog-->onPositivePressEvent');
              Navigator.of(Get.context).pop();
              startForbiddenPerson(voicePerson);
            },
            onCloseEvent: (){
              LogUtil.d('showDialog-->onCloseEvent');
              Navigator.of(Get.context).pop();
            },
          );
        }
    );
  }
  startForbiddenPerson(VoicePersonEntity voicePerson)async{
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    //关系类型:2:管理员,3:主播,4:黑名单,6:禁言
    Map<String,dynamic> upData={
      "relationType": 6,
      "roomId": roomInfo?.id,
      "userId": voicePerson?.userId
    };
    LogUtil.d('toMyRoom--->upData=$upData,isCloseWheat=${isCloseWheat(voicePerson)},relationType=${voicePerson?.relationType}');
    LoadUtil.hideLoad();
    BaseEntity baseEntity = await moduleIndexService.
    api_voicechat_room_bindOrUnBindUserRoomRelation(parmsMap: upData,isBind: !isCloseWheat(voicePerson));
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      await NIMSDKUtil.instance.markChatroomMemberMuted(
          isAdd: !isCloseWheat(voicePerson),
          roomId: roomYxInfo.value.roomId,
          account: voicePerson?.yxAccid
      );
      update();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  bool isCloseWheat(VoicePersonEntity voicePerson) {
    if(voicePerson?.identityType == '6')return true;
    return false;
  }
  bool isForbidden(VoicePersonEntity voicePerson) {
    if(voicePerson?.identityType == '6')return true;
    return false;
  }

  void getMyFollows() async{
    Map<String,dynamic> upData={
      "currentPage":1,
      "pageSize":100000,
      "type":3,
      // "keyword":"tp"
    };
    myFollowIds.clear();
    BaseEntity baseEntity = await moduleMyService.api_user_userFriend(parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      List<UserEntity> myFollowTemps = baseEntity?.result??[];
      if(myFollowTemps.isNotEmpty)myFollowIds = myFollowTemps.map((e) => e?.userId).toList();
    }
    update();
  }

  bool isFollow(VoicePersonEntity micMember) {
    return myFollowIds.contains(micMember?.userId??(-1000));
  }
  //关注与取关
  void toFollowPerson(VoicePersonEntity voicePerson) async{
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    Map<String,dynamic> upData={
      "followUserId": voicePerson?.userId
    };
    if(isFollow(voicePerson)){
      upData['followType']=2;
    }else{
      upData['followType']=1;
    }
    BaseEntity baseEntity = await moduleMyService.api_user_followUser(parmsMap: upData);
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      //重新获取关注的列表
      getMyFollows();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  void toChat(VoicePersonEntity micMember) {
    if(isMySelf(currVoicePersonEntity?.userId, micMember?.userId))return;
    NavigatorUtil.pushByName(RouteConfig.chatPage,arguments: {
      'voicePersonEntity':micMember,
      'voicePersonUserId':'${micMember?.userId}',
      'voicePersonYxAccid':micMember?.yxAccid,
      'voicePersonNickName':micMember?.nickname,
      'voicePersonIcon':micMember?.icon,
    });
  }

  doCollectRoom() async{
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    Map<String,dynamic> upData={
      "searchValue": roomInfo?.id
    };
    BaseEntity baseEntity = await moduleIndexService.api_voicechat_room_collectionOrUnRoom(
        parmsMap: upData,isCollection: !isCollect.value);
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      checkCollect();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  void checkCollect() async{
    Map<String,dynamic> upData={
      "searchValue": roomInfo?.id
    };
    BaseEntity baseEntity = await moduleIndexService.api_voicechat_room_queryUserCollectionRoomState(
        parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      isCollect.value = baseEntity?.result??false;
      LogUtil.d('checkCollect--->isCollect=$isCollect');
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  onOpenGifts({List<UserEntity> defaultPersons}) {
   var  upMicPersons = (defaultPersons??[]).where((element) => (element?.yxAccid??'').isNotEmpty).toList();
    DialogUtil.instance.showCommBottomSheet(
        isScrollControlled: true,
        child: RoomGiftsBottomSheetWidget(
          yxRoomId: roomInfo?.yxRoomId,
          roomId: roomInfo?.id,
          defaultPersons: defaultPersons??[],
          // toUsers: upMicPersons,
          onSend: (GiftEntity giftEntity,int giftNum,List<UserEntity> toUsers){
            NavigatorUtil.goBack();
            LogUtil.d('openGiftsUi-->giftNum=$giftNum,giftEntity=${giftEntity?.toJson()}');
            LogUtil.d('openGiftsUi-->toUser=${(toUsers??[]).map((e) => e?.toJson()).toList()}');
            //发起送礼
            sendGifts(giftEntity,giftNum,toUsers);
          },
        )
    );
  }
  void sendGifts(GiftEntity giftEntity, int giftNum,List<UserEntity> toUsers) async{
    LoadUtil.showLoad(loadingText: StringUtil.instance.Sending);
    Map<String,dynamic> parmsMap= {
      "giftId": giftEntity?.id,
      "giftNum": giftNum,
      "payType": 1,
      "roomId": roomInfo?.id,
      "userId": (toUsers??[]).map((e) => e?.userId).toList()
    };
    LogUtil.d('sendGifts--->parmsMap=$parmsMap');
    LogUtil.d('sendGifts--->myuserId=${UserParamsModel.instance.userId}');
    BaseEntity baseEntity = await moduleMyService.api_voicechat_gift_sendGift(parmsMap: parmsMap);
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      ToastUtil.toast(StringUtil.instance.Send_success);
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }
}
